<?php
/**
 *根据本地数据库生成数据字典
 *字典位置 : /Data/Doc/db.md
 */
error_reporting(0);
PHP_SAPI == 'cli' or exit('use cli');
chdir(__DIR__ . "/../..");

function query ($sqlOrConfig)
{
    static $resConfig;
    if (is_array($sqlOrConfig))
    {
        $resConfig = $sqlOrConfig;
        $link = mysql_connect($resConfig['DB_HOST'] . ':' . $resConfig['DB_PORT'], $resConfig['DB_USER'], $resConfig['DB_PWD'], true) or exit('Can not connect to db host');
        mysql_query("use " . $resConfig['DB_NAME']) or exit('Can not use db');
        mysql_query('set names utf8');
        return true;
    }
    
    $sql = @str_replace('@p_', $resConfig['DB_PREFIX'], $sqlOrConfig);
    $res = mysql_query($sql);
    if (is_bool($res))
    {
        return $res;
    }
    
    $arr = array();
    while ($row = mysql_fetch_array($res, MYSQL_ASSOC))
    {
        $arr[] = $row;
    }
    return $arr;
}

function print_table ($table, $i)
{
    $md = [];
    $tablename = "## [{$i}] {$table['TABLE_NAME']}";
    $tableinfo = "##### " . ($table['TABLE_COMMENT'] ? "{$table['TABLE_COMMENT']}  " : "") . $table['ENGINE'];
    $col[] = [
            'Column',
            'Type',
            'Default',
            'Not null',
            'Comment'
    ];
    $col[] = array_pad([], count($col[0]), ':----------');
    foreach ($table['cols'] as $v)
    {
        $col[] = [
                $v['COLUMN_NAME'],
                $v['COLUMN_TYPE'],
                $v['COLUMN_DEFAULT'],
                $v['IS_NULLABLE'],
                $v['COLUMN_COMMENT']
        ];
    }
    $collist = "";
    foreach ($col as $v)
    {
        foreach ($v as $vv)
        {
            $collist .= str_pad("|" . trim($vv), 26, ' ');
        }
        $collist .= "|\n";
    }
    return "$tablename\n$tableinfo\n$collist";
}

$config = require 'config.php';
$config = require '../config.php';
file_exists('../config.dev.php') and $config = array_merge($config, require '../config.dev.php');
file_exists('../config.product.php') and $config = array_merge($config, require '../config.product.php');

$dir = "../Data/Doc/";
file_exists($dir) or mkdir($dir, 0777, true) and chmod($dir, 0777);
$file = $dir . 'db.md';

query($config);
$sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_schema='{$config['DB_NAME']}' ORDER BY TABLE_NAME ASC";
$tables = query($sql);
foreach ($tables as &$v)
{
    $sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name='{$v['TABLE_NAME']}' AND table_schema='{$config['DB_NAME']}' ORDER BY ORDINAL_POSITION ASC";
    $v['cols'] = query($sql);
}

$md = [];
$md[] = "#数据字典";
$md[] = "数据库 : {$config['DB_NAME']}  ";
$md[] = "生成日期 : " . date('Y-m-d');
$md[] = '';
foreach ($tables as $k => $v)
    $md[] = print_table($v, $k + 1);

file_put_contents($file, implode("\n", $md));

echo "Database dictionary file : $file\n";